<?
require_once($r."_config/db.php");
require_once($r."_config/site.php");
require_once($r."_engine/c_sql_table.php");

define("RESOURCE_STORAGE_STATUS_ERROR",			0x00);
define("RESOURCE_STORAGE_STATUS_FAKE",			0x01);
define("RESOURCE_STORAGE_STATUS_NOT_CHANGE",	0x02);
define("RESOURCE_STORAGE_STATUS_CHANGED",		0x03);
define("RESOURCE_STORAGE_STATUS_TRIGGERED",		0x04);

$g_st_res_storage = new CSqlTable("resources_storage", "id");
$g_st_res_storage->field_types["download_dt"] = "dt";

class CResStorage
{
	var $id, $data;
	
	function LoadById($id, $short=false)
	{
		$fields = "*";
		if ($short) {
			$fields = 
				"id, monitor_id, download_dt, effective_url, ".
				"resource_src_size, resource_is_compressed";
		}
		return $this->LoadByQuery(
			"SELECT $fields FROM resources_storage WHERE id='$id';"
		);
	}
	function LoadPrevFor($id)
	{
		return $this->LoadByQuery(
			"SELECT * FROM resources_storage WHERE id < '$id' ORDER BY id DESC LIMIT 0, 1;"
		);
	}
	function LoadByQuery($query)
	{
		global $g_st_res_storage;
		$row = $g_st_res_storage->SelectRow($query);
		if (!$row) return false;
		$this->LoadFromArray($row);
		return true;
	}
	
	function LoadFromArray($row)
	{
		foreach($row as $f => $v)
		{
			if (is_int($f)) continue;
			
			if ($f == "id")
				$this->id = $v;
			else
				$this->data[$f] = $v;
		}
	}
	
	function GetScanDT()
	{
		$dt = $this->data["download_dt"];

		global $account;
		if (isset($account)) $dt = $account->TimeToUserTZ($dt);

		return $dt;
	}
	
	function GetScanDTStr()
	{
		return @date("M j, Y H:i", $this->GetScanDT());
	}
	
	function GetScanResult($prev=NULL)
	{
		if ($prev == NULL)
		{
			$prev = new CResStorage();
			$prev->LoadPrevFor($this->id);
		}
		$f = ($prev != NULL && @$prev->data["resource_status"] == RESOURCE_STORAGE_STATUS_FAKE);
		
		$s_lfv = "Mon 1st time";
		
		switch ($this->data["resource_status"]) 
		{
			case RESOURCE_STORAGE_STATUS_ERROR:
				return "Error";
				break;
			case RESOURCE_STORAGE_STATUS_FAKE:
				// should not be visible for user
				return "";
				break;
			case RESOURCE_STORAGE_STATUS_NOT_CHANGE:
				if ($f) 
					return $s_lfv;
				else
					return "Not Changed";
				break;
			case RESOURCE_STORAGE_STATUS_CHANGED:
				if ($f) 
					return $s_lfv;
				else
					return "Changed";
				break;
			case RESOURCE_STORAGE_STATUS_TRIGGERED:
				if ($f) 
					//return $s_lfv . " - notified";
					return "Keyword Found and Notified";
				else
					return "Changed & Notified";
				break;
			default:
				return "";
				break;
		}
	}
}

function GetLastChangedItem($monitor_id)
{
	$res = execute_query('
SELECT id, download_dt
FROM resources_storage
WHERE
    monitor_id = '.$monitor_id.' AND
    (resource_status = '.RESOURCE_STORAGE_STATUS_CHANGED.' OR
     resource_status = '.RESOURCE_STORAGE_STATUS_TRIGGERED.')
ORDER BY id DESC
LIMIT 0, 1;
    ');
    
    
    
	if (!($row = @mysql_fetch_array($res))) {
        return false;
    }
    
    return array(
        'dt'    => @date("M j, Y", strtotime($row['download_dt'])),
        'href'  => 'history_nav.php?monitor_id='.$monitor_id.'&resource_id='.$row["id"],
    );
}

function GetFirstMonitoredItem($monitor_id)
{
	$res = execute_query('
SELECT
    id, download_dt
FROM
    resources_storage
WHERE
    monitor_id = '.$monitor_id.' AND
    resource_status <> '.RESOURCE_STORAGE_STATUS_FAKE.'
ORDER BY id ASC
LIMIT 0, 1;
    ');
    
	return @mysql_fetch_array($res);
}

function GetResStorageList($monitor_id, $num, &$rsl)
{
	$rsl = array();
	
	$res = execute_query(
		"SELECT ".
			"`id`, `monitor_id`, `download_dt`, `resource_src_size`, `resource_is_compressed`, ".
			"`curl_code`, `curl_message`, `http_response_code`, `http_response_header`,	".
			"`resource_status`, `qty_added`, `qty_deleted`, `qty_triggers` ".
		" FROM resources_storage".
		" WHERE monitor_id=".$monitor_id.
		" ORDER BY id DESC".
		" LIMIT 0, ".$num.";");
		
	while ($row = @mysql_fetch_array($res))
	{
		global $g_st_res_storage;
		$g_st_res_storage->DecodeValues($row);
		
		$rs = new CResStorage();
		$rs->LoadFromArray($row);
		$rsl[] = $rs;
	}
}

function GetNextPrevRes($monitor_id, $resource_id, $dir, &$is_fake)
{
	/* $dir: true - next, false - prev */
	
	$sign = ($dir ? ">" : "<");
	$order = ($dir ? "ASC" : "DESC");

	$res = execute_query($q=
		"SELECT ".
			"`id`, `resource_status` ".
		"FROM resources_storage ".
		"WHERE ".
			"`monitor_id`=$monitor_id AND ".
			"`id` $sign $resource_id AND ".
			"(`resource_status`= ".RESOURCE_STORAGE_STATUS_FAKE." OR ".
			" `resource_status`= ".RESOURCE_STORAGE_STATUS_CHANGED." OR ".
			" `resource_status`= ".RESOURCE_STORAGE_STATUS_TRIGGERED.") ".
		"ORDER BY id $order ".
		"LIMIT 0, 1;");
	//var_dump($q);

	if (!($row = @mysql_fetch_array($res)))
	{
		return -1;

	}
	
	$is_fake = ($row["resource_status"] == RESOURCE_STORAGE_STATUS_FAKE);
	return $row["id"];
}


function GetCalendarForDownload($monitor_id, $resource_id, $dt,
    &$prev, &$list, &$next)
{
    $days_in_month = date("t", $dt);
    for ($i = 1; $i <= $days_in_month; $i++)
    {
        $list[$i] = false;
    }

    $res = execute_query($q='
        SELECT
           id, resource_status, download_dt
        FROM
            resources_storage
        WHERE
            monitor_id = '.$monitor_id.' AND
            download_dt LIKE \''.date("Y-m-", $dt).'%\' AND
            resource_status <> '.RESOURCE_STORAGE_STATUS_FAKE.'
        ORDER BY id ASC;
    ');
    //var_dump($q);

    $min_id = $max_id = $resource_id;
    while ($row = @mysql_fetch_array($res))
    {
        //var_dump($row);
        //echo $row["id"]." ".$row["resource_status"]." ".$row["download_dt"]."<br>";
        
        $min_id = min($min_id, $row["id"]);
        $max_id = max($max_id, $row["id"]);
        
        $d = date("j", strtotime($row["download_dt"]));
        $list[$d] = $row;
    }
    //echo $min_id." ".$max_id;


    $res = execute_query($q='
        SELECT
           id, resource_status, download_dt
        FROM
            resources_storage
        WHERE
            monitor_id = '.$monitor_id.' AND
            ( resource_status = '.RESOURCE_STORAGE_STATUS_CHANGED.' OR
              resource_status = '.RESOURCE_STORAGE_STATUS_TRIGGERED.' )
        ORDER BY id ASC
        LIMIT 0, 1;
    ');
    //var_dump($q);
    $prev = @mysql_fetch_array($res);
	if (@$prev["id"] == $resource_id) $prev = false;

    $res = execute_query($q='
        SELECT
           id, resource_status, download_dt
        FROM
            resources_storage
        WHERE
            monitor_id = '.$monitor_id.' AND
            ( resource_status = '.RESOURCE_STORAGE_STATUS_CHANGED.' OR
              resource_status = '.RESOURCE_STORAGE_STATUS_TRIGGERED.' )
        ORDER BY id DESC
        LIMIT 0, 1;
    ');
    //var_dump($q);
    $next = @mysql_fetch_array($res);
	if (@$next["id"] == $resource_id) $next = false;
}


/* TODO: Move to functions.php and revise all other functions */
function decode_number_by_weights($x, $weights)
{                        
    $r = array();

    foreach ($weights as $k => $w)
    {
        if ($w == 0) {
            $r[$k] = $x;
            break;
        }
        
    	$r[$k] = $x % $w;
        $x = floor($x / $w);
    }
    
    return $r;
}

function get_last_monitored_time_str($x)
{
	if ($x == "") return "";
    
    $now = gmt_time("now");
    $dif = $now - $x;

    $offs = decode_number_by_weights($dif, array(
        "sec"  => 60,
        "min"  => 60,
        "hour" => 24,
        "day"  => 7,
        "week" => 4,
        "month" => 0,
    ));
           
    $s = "";
    
    $offs_r = array_reverse($offs);
    foreach($offs_r as $k => $v) 
    {
        if ($v != 0 || $k == "sec") 
        {
            $s .= $v." ".$k;
            $s .= ($v > 1 ? "s" : "");
            break;
        }
    }
        
	return $s . " ago";
}

function get_last_monitored_periodicity($x)
{
    global $g_monitor_frequency_map;
    $s = "";
    
    if (isset($g_monitor_frequency_map[$x])) {
        $s = $g_monitor_frequency_map[$x];
    }
    else {
        $s = "Each ".$x." secs";
    }
    
    return $s;
}
?>